import { useUserStore } from '@/store/modules/user';
import { useSocket, UseSocketReturn } from '@uni-helper/uni-use'
import { IMMessageType } from '@/enmus/IMMessageEnum';
import { getToken } from '@/utils/auth';
import { MessageVo } from '@/types/IMMessageDTO';
import { useIMStore } from '@/store/modules/im';

export const useSocketStore = defineStore('webSocket', () => {


  const socketInstance= ref<UseSocketReturn>(null)

  const initSocket = () => {
    if (!getToken() || import.meta.env.VITE_APP_WEBSOCKET === 'false') {
      return;
    }
    if (!socketInstance.value) {
      const url = setRequestUrl() + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
      socketInstance.value = useSocket(url, {
        autoReconnect: {
          // 重连最大次数
          retries: -1,
          // 重连间隔
          delay: 1000,
          onFailed() {
            console.log('websocket重连失败');
          }
        },
        heartbeat: {
          message: JSON.stringify({ messageType: IMMessageType.PING, receiveUser: new Array(useUserStore().userId) }),
          // 发送心跳的间隔
          interval: 10000,
          // 接收到心跳response的超时时间
          pongTimeout: 2000
        },
        onConnected() {
          console.log('websocket已经连接');
        },
        onDisconnected() {
          console.log('websocket已经断开');
        },
        onMessage: (_, e) => {
          if (!e.data) return;
          if (e.data.indexOf(IMMessageType.PING) > 0) return;

          const message: MessageVo = JSON.parse(e.data);
          uni.$emit(message.messageType, message);
          if (!message.ifRead && message.ifUpCount) {
            useIMStore().add(message.messageType);
          }
          if (message.ifHint && message.messageType !== IMMessageType.LOGIN) {
            modal.showIMMessage(message.messageTitle, message.messageInfo);
          }
        }

      })
    }
  }
  const sendSocketMessage=(message: MessageBo)=>{
    if (!socketInstance.value) {
      console.error('WebSocket 未初始化');
      return;
    }
    message.messageType = message.messageType == null ? IMMessageType.SYSTEM : message.messageType;
    message.sendTime = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss');
    message.sendUser = useUserStore().userId;
    if (!socketInstance.value.isClosed) {
      socketInstance.value.send(JSON.stringify(message));
    } else {
      console.error('WebSocket连接未打开，无法发送消息');
    }
  }
  //关闭链接
  const closeWebSocket = () => {
    if (!socketInstance.value) {
      console.error('WebSocket 未初始化');
      return;
    }
    if (socketInstance.value.isClosed) {
      socketInstance.value.close();
    }
  };
  //处理websocket的请求地址
  const setRequestUrl = () => {
    let url = '';
    const api = import.meta.env.VITE_APP_BASE_API;
    if (api.startsWith('http://')) {
      // 如果是http协议，则使用ws协议
      url = api.replace('http://', 'ws://');
    } else if (api.startsWith('https://')) {
      url = api.replace('https://', 'wss://');
    } else {
      const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
      url = `${protocol}${window.location.host}${import.meta.env.VITE_APP_BASE_API}`;
    }
    return `${url}/resource/websocket`;
  };

  return {
    initSocket,
    sendSocketMessage,
    closeWebSocket
  }

});

export default useSocketStore;


